/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef PANDA_TOOLING_TEST_JS_EXCEPTION_EVENTS_TEST_H
#define PANDA_TOOLING_TEST_JS_EXCEPTION_EVENTS_TEST_H

#include "test_util.h"
#include "runtime/include/tooling/pt_location.h"

namespace ark::tooling::test {
class JsExceptionEventTest : public ApiTest {
public:
    JsExceptionEventTest()
    {
        vmDeath = [this]() {
            ASSERT_EQ(exceptionCounter_, 1U);
            ASSERT_EQ(exceptionCatchCounter_, 1U);
            return true;
        };

        methodEntry = [this](PtThread thread, Method *method) {
            if (method->GetFullName() == "_GLOBAL::func_main_0") {
                ASSERT_TRUE(threadId_ == PtThread::NONE.GetId());
                threadId_ = thread.GetId();
            }
            return true;
        };

        methodExit = [this](PtThread, Method *method, bool, VRegValue) {
            if (method->GetFullName() == "_GLOBAL::func_main_0") {
                threadId_ = PtThread::NONE.GetId();
            }
            return true;
        };

        exception = [this](PtThread thread, Method *, const PtLocation &, ObjectHeader *, Method *,
                           const PtLocation &catchLocation) {
            if (threadId_ != thread.GetId()) {
                return true;
            }

            ++exceptionCounter_;
            catchLocation_ = catchLocation;
            return true;
        };

        exceptionCatch = [this](PtThread thread, Method *, const PtLocation &location, ObjectHeader *) {
            if (threadId_ != thread.GetId()) {
                return true;
            }

            ASSERT_LOCATION_EQ(location, catchLocation_);
            ++exceptionCatchCounter_;
            return true;
        };
    }

    std::pair<const char *, const char *> GetEntryPoint() override
    {
        return {pandaFile_.c_str(), entryPoint_.c_str()};
    }

private:
    std::string pandaFile_ = "js/ExceptionTest.abc";
    std::string entryPoint_ = "_GLOBAL::func_main_0";
    size_t exceptionCounter_ = 0;
    size_t exceptionCatchCounter_ = 0;
    uint32_t threadId_ = PtThread::NONE.GetId();
    PtLocation catchLocation_ {nullptr, PtLocation::EntityId(0), 0};
};

inline std::unique_ptr<ApiTest> GetJsExceptionEventTest()
{
    return std::make_unique<JsExceptionEventTest>();
}
}  // namespace ark::tooling::test

#endif  // PANDA_TOOLING_TEST_JS_EXCEPTION_EVENTS_TEST_H
